package com.example.module_motocircle.ui.post.detail.adapter

import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListUpdateCallback
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.example.module_motocircle.R
import com.example.module_motocircle.databinding.ItemAfterSaleInfoBinding
import com.example.module_motocircle.databinding.ItemCommentFirstLevelBinding
import com.example.module_motocircle.databinding.ItemCommentFooterBinding
import com.example.module_motocircle.databinding.ItemCommentHeaderBinding
import com.example.module_motocircle.databinding.ItemCommentSecondLevelBinding
import com.example.module_motocircle.databinding.ItemPostDetailBinding
import com.example.module_motocircle.model.CommentsModel
import com.example.module_motocircle.model.PostCommentsModel
import com.example.module_motocircle.model.PostModel
import com.example.module_motocircle.ui.post.detail.AfterSalePageItem
import com.example.module_motocircle.ui.post.detail.CommentItem
import com.example.module_motocircle.ui.post.detail.PostItem

class PostDetailAdapter(
    private val muber:Int =2 , private val isOnlyTpye:Boolean =false
):RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    class CommentsDiffUtil(private val oldData: List<PostCommentsModel>, private val newData: List<PostCommentsModel>) : DiffUtil.Callback() {
        override fun getOldListSize(): Int {
            return oldData.size
        }

        override fun getNewListSize(): Int {
            return newData.size
        }

        override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return oldData[oldItemPosition].postsCommentId == newData[newItemPosition].postsCommentId
        }

        override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return (oldData[oldItemPosition].content == newData[newItemPosition].content &&
                    oldData[oldItemPosition].pinned == newData[newItemPosition].pinned &&
                    oldData[oldItemPosition].twoLevelSize == newData[newItemPosition].twoLevelSize &&
                    oldData[oldItemPosition].topRound == newData[newItemPosition].topRound &&
                    oldData[oldItemPosition].bottomRound == newData[newItemPosition].bottomRound &&
                    oldData[oldItemPosition].like_number == newData[newItemPosition].like_number)
        }

        override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
            return (oldData[oldItemPosition].content == newData[newItemPosition].content &&
                    oldData[oldItemPosition].pinned == newData[newItemPosition].pinned &&
                    oldData[oldItemPosition].isLike == newData[newItemPosition].isLike &&
                    oldData[oldItemPosition].like_number == newData[newItemPosition].like_number &&
                    oldData[oldItemPosition].twoLevelSize == newData[newItemPosition].twoLevelSize &&
                    oldData[oldItemPosition].topRound == newData[newItemPosition].topRound &&
                    oldData[oldItemPosition].bottomRound == newData[newItemPosition].bottomRound)
        }


    }

    //private var postItem: PostItem? = null
    private var postModel: PostModel? = null
    private var afterSale:List<AfterSalePageItem>? = null
    private var comments:MutableList<PostCommentsModel> = mutableListOf()
    private var hasAfterSale:Int = 0
    var totalCommentsSize: Int = 0
    var m1stPageCommentsSize: Int = 0

    var haveAfterSaleInfo: Int = 0

    //评论列表前原始数据偏移 帖子详情+header
    private val mCommentOffsetInData
        get() =
            muber + haveAfterSaleInfo
    private val callback = object : ListUpdateCallback {
        override fun onInserted(position: Int, count: Int) {
            this@PostDetailAdapter.notifyItemRangeInserted(position + mCommentOffsetInData, count)
            this@PostDetailAdapter.notifyItemChanged(position + mCommentOffsetInData - 1, count + 1)
        }

        override fun onRemoved(position: Int, count: Int) {
            this@PostDetailAdapter.notifyItemRangeRemoved(position + mCommentOffsetInData, count)
        }

        override fun onMoved(fromPosition: Int, toPosition: Int) {
            this@PostDetailAdapter.notifyItemMoved(fromPosition + mCommentOffsetInData, toPosition + mCommentOffsetInData)

        }

        override fun onChanged(position: Int, count: Int, payload: Any?) {
            this@PostDetailAdapter.notifyItemRangeChanged(position + mCommentOffsetInData, count)
        }
    }

    fun setCommentsNewData(newComments: MutableList<PostCommentsModel>) {
        val ret = DiffUtil.calculateDiff(CommentsDiffUtil(comments, newComments), true)
        this.comments.clear()
        this.comments.addAll(newComments)
        notifyItemRangeChanged(0, mCommentOffsetInData)
        ret.dispatchUpdatesTo(callback)

    }



    override fun getItemViewType(position: Int): Int {
        if(hasAfterSale == 1){// 售后 详情 头 评论。。。。 尾
            return when (position) {
                0 -> Type.AFTER_SALE_INFO.value
                1 -> Type.POST.value
                2 -> Type.COMMENTS_HEADER.value
                in 3..comments.size + 2 -> {
                    return if (comments[position - 3].isFirstLevel) Type.FIRST_COMMENTS.value else Type.SECOND_COMMENTS.value
                }
                else -> Type.COMMENTS_FOOTER.value
            }
        }else{
            return when (position) {
                0 -> Type.POST.value
                1 -> Type.COMMENTS_HEADER.value
                in 2..comments.size + 1 -> { //3
                    return if (comments[position - 2].isFirstLevel) Type.FIRST_COMMENTS.value else Type.SECOND_COMMENTS.value
                }
                else -> Type.COMMENTS_FOOTER.value
            }
        }
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when(viewType){
            Type.AFTER_SALE_INFO.value -> {
                val binding: ItemAfterSaleInfoBinding = DataBindingUtil.inflate(
                    LayoutInflater.from(parent.context),
                    R.layout.item_after_sale_info,
                    parent,
                    false
                )
                return AfterSaleViewHolder(binding.root)
            }
            Type.POST.value -> {
                val binding: ItemPostDetailBinding = DataBindingUtil.inflate(
                    LayoutInflater.from(parent.context),
                    R.layout.item_post_detail,
                    parent,
                    false
                )
                val postDetailsViewModel = PostDetailsViewHolder(binding.root)
                binding.holder = postDetailsViewModel
                return postDetailsViewModel
            }
            Type.COMMENTS_HEADER.value -> {
                val binding: ItemCommentHeaderBinding = DataBindingUtil.inflate(
                    LayoutInflater.from(parent.context),
                    R.layout.item_comment_header,
                    parent,
                    false
                )
                return CommentHeaderViewHolder(binding.root)
            }
            Type.FIRST_COMMENTS.value -> {
                val binding: ItemCommentFirstLevelBinding = DataBindingUtil.inflate(
                    LayoutInflater.from(parent.context),
                    R.layout.item_comment_first_level,
                    parent,
                    false
                )
                return CommentFirstViewHolder(binding.root)
            }
            Type.SECOND_COMMENTS.value -> {
                val binding: ItemCommentSecondLevelBinding = DataBindingUtil.inflate(
                    LayoutInflater.from(parent.context),
                    R.layout.item_comment_second_level,
                    parent,
                    false
                )
                return CommentSecondViewHolder(binding.root)
            }
            else -> {
                val binding: ItemCommentFooterBinding = DataBindingUtil.inflate(
                    LayoutInflater.from(parent.context),
                    R.layout.item_comment_footer,
                    parent,
                    false
                )
//                return CommentFooterViewHolder(binding.root)
                return CommentFooterViewHolder(binding, totalCommentsSize, m1stPageCommentsSize)

            }
        }

    }
    fun setPostInfo(post: PostModel?, totalSize: Int, _1stSize: Int) {
        this.postModel = post
        this.totalCommentsSize = totalSize
        this.m1stPageCommentsSize = _1stSize
        notifyItemRangeChanged(0, mCommentOffsetInData)
        notifyItemChanged(itemCount)
    }


    override fun getItemCount(): Int {
        return hasAfterSale + comments?.size !! + 3

    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when(getItemViewType(position)){
            Type.AFTER_SALE_INFO.value -> {
            }

            Type.POST.value -> {
                val binding = DataBindingUtil.getBinding<ItemPostDetailBinding>(holder.itemView)
                binding?.post = postModel
                postModel ?: return
                (holder as PostDetailsViewHolder).initView(postModel!!, position)
                binding?.lLocation?.setOnClickListener {
                    //onClickLocation?.invoke(postModel!!)
                }

                binding?.lFollowState?.isSelected = postModel?.hasFollowed() ?: false
            }

            Type.COMMENTS_HEADER.value -> {
                val binding = DataBindingUtil.getBinding<ItemCommentHeaderBinding>(holder.itemView)
                binding?.tvCommentsNum?.text = String.format("%d 条评论", totalCommentsSize)
            }

            Type.FIRST_COMMENTS.value -> {
                val binding = DataBindingUtil.getBinding<ItemCommentFirstLevelBinding>(holder.itemView)
                binding?.let {
                    val comment = comments[position - mCommentOffsetInData]
                    it.comments = comment
                    it.viewHolder = holder as CommentFirstViewHolder
                    //点击评论
                    it.root.setOnClickListener {
//                        val body = PostCommentBody().apply {
//                            this.postsId = comment.postsId
//                            this.parentId = comment.postsCommentId
//                            this.firstCommentId = comment.postsCommentId
//                            this.beReplyId = comment.createBy
//                        }
//                        onClickComments?.invoke(body, comment.requireCreateName())
                    }
                    if (comment.oneself == true) {
                        it.root.setOnLongClickListener {
//                            onDeleteComment?.invoke(comment.postsCommentId)
                            true
                        }
                    }
                    it.lLike.setOnClickListener {
//                        onClickLikeView?.invoke(comment.postsId, comment.postsCommentId, binding.ivLike, comment.isLike == 1) {
//                            val findComment = comments.find { t -> t.postsCommentId == comment.postsCommentId } ?: return@invoke
//                            val findPosition = comments.indexOf(findComment)
//                            handleClickLike(findComment)
//                            notifyItemChanged(findPosition + mCommentOffsetInData)
//                        }
                    }
                }
            }

            Type.SECOND_COMMENTS.value -> {
                val binding = DataBindingUtil.getBinding<ItemCommentSecondLevelBinding>(holder.itemView)
                binding?.let {
                    val comment = comments[position - mCommentOffsetInData]
                    it.comments = comment
                    it.viewHolder = holder as CommentSecondViewHolder
                    it.root.setOnClickListener {
//                        val body = PostCommentBody().apply {
//                            this.postsId = comment.postsId
//                            this.parentId = comment.postsCommentId
//                            this.firstCommentId = comment.firstCommentId
//                            this.beReplyId = comment.createBy
//                        }
//                        onClickComments?.invoke(body, comment.requireCreateName())
                    }
                    //圆角处理
                    if (comments[position - mCommentOffsetInData].topRound) it.l2ndComments.setBackgroundResource(R.drawable.shape_bg_mask_round_top_4dp)
                    if (comments[position - mCommentOffsetInData].bottomRound) it.l2ndComments.setBackgroundResource(R.drawable.shape_bg_mask_round_bottom_4dp)
                    if (comments[position - mCommentOffsetInData].rect) it.l2ndComments.setBackgroundResource(R.drawable.shape_bg_mask_rect)
                    if (comment.oneself == true) {
                        it.root.setOnLongClickListener {
//                            onDeleteComment?.invoke(comment.postsCommentId)
                            true
                        }
                    }
                    it.lLike.setOnClickListener {

//                        onClickLikeView?.invoke(comment.postsId, comment.postsCommentId, binding.ivLike, comment.isLike == 1) {
//                            val findComment = comments.find { t -> t.postsCommentId == comment.postsCommentId } ?: return@invoke
//                            val findPosition = comments.indexOf(findComment)
//                            handleClickLike(findComment)
//                            notifyItemChanged(findPosition + mCommentOffsetInData)
//                        }
                    }
                }
            }

            Type.COMMENTS_FOOTER.value -> {
                val binding = DataBindingUtil.getBinding<ItemCommentFooterBinding>(holder.itemView)
                //重新设置评论数据
                (holder as CommentFooterViewHolder).setCommentsSize(totalCommentsSize, m1stPageCommentsSize)
                binding?.viewHolder = holder
                //footer状态切换
//                noMore = holder::noMore
//                loading = holder::loading
//                error = holder::error
            }

        }

    }

    fun setPostItem(postItem: PostModel,totalSize: Int){
        this.postModel = postItem
        this.totalCommentsSize = totalSize
        notifyDataSetChanged()
    }

    fun setAfterSale(list: List<AfterSalePageItem>){
        this.afterSale = afterSale
        if(list.isNullOrEmpty()){
            hasAfterSale = 1
        }
        notifyDataSetChanged()
    }

    fun setComments(list: MutableList<PostCommentsModel>){
        this.comments = list
        notifyDataSetChanged()
    }



    enum class Type(val value: Int) {
        POST(1), COMMENTS_HEADER(2), FIRST_COMMENTS(3), SECOND_COMMENTS(4), COMMENTS_FOOTER(5), AFTER_SALE_INFO(6)
    }

}

class AfterSaleViewHolder(itemView: View):RecyclerView.ViewHolder(itemView)
class CommentFirstViewHolder(itemView: View, val onUserClick: ((String, Boolean) -> Unit)? = null) : RecyclerView.ViewHolder(itemView) {
    val mBinding: ItemCommentFirstLevelBinding by lazy {
        DataBindingUtil.getBinding(itemView)!!
    }

    fun clickUser() {
        if (mBinding.comments?.isOfficial() == true)
            return
        onUserClick?.invoke(mBinding.comments!!.createBy, false)
    }
}
class CommentSecondViewHolder(
    itemView: View,
    //val haveAfterSaleInfo: Boolean = false,
//    private val clickShowAll: (CommentsModel, Int) -> Unit,
    val onUserClick: ((String, Boolean) -> Unit)? = null
) :
    RecyclerView.ViewHolder(itemView) {
    val mBinding: ItemCommentSecondLevelBinding by lazy {
        DataBindingUtil.getBinding(itemView)!!
    }

    fun clickAllComments(comments: CommentsModel) {
        //clickShowAll.invoke(comments, this.absoluteAdapterPosition - if (haveAfterSaleInfo) 3 else 2)
    }

    //格式化回复评论内容 XXX回复：YY
    fun formatReplayContent(content: String, replyName: String?): CharSequence {
        val prefix = String.format("%s", replyName ?: "未知用户")
        val formatContent = String.format("回复%s：%s", prefix, content)
        val start = formatContent.indexOf(prefix)
        val end = start + prefix.length
        val spannableStringBuilder = SpannableStringBuilder(formatContent)
        spannableStringBuilder.setSpan(
            ForegroundColorSpan(ContextCompat.getColor(itemView.context, R.color.color_919191)),
            start,
            end,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        return spannableStringBuilder
    }

    fun clickUser() {
        if (mBinding.comments?.isOfficial() == true)
            return
        onUserClick?.invoke(mBinding.comments!!.createBy, false)
    }


}
class CommentHeaderViewHolder(itemView: View):RecyclerView.ViewHolder(itemView)
//class CommentFooterViewHolder(itemView: View):RecyclerView.ViewHolder(itemView)
class CommentFooterViewHolder(
    val binding: ItemCommentFooterBinding,
//    private val onClickLoadMore: (() -> Boolean)? = null,
//    private val onClickRetry: (() -> Unit)? = null,
    private var totalCommentSize: Int,
    private var m1stPageCommentsSize: Int
) :
    RecyclerView.ViewHolder(binding.root) {

    fun setCommentsSize(total: Int, m1stPageSize: Int) {
        this.totalCommentSize = total
        this.m1stPageCommentsSize = m1stPageSize
    }

    //是否显示
    fun show(): Boolean {
        val size = totalCommentSize - m1stPageCommentsSize
        return size > 0 && totalCommentSize > 10 && m1stPageCommentsSize >= 10
    }

    //format剩余评论数据
    fun formatRemainingCommentsNum(): String {
        val size = totalCommentSize - m1stPageCommentsSize
        return String.format("展开%d评论", size)
    }

    //点击加载更多
    fun loadMore() {
//        if (onClickLoadMore?.invoke() != true)
            return
    }

    private fun retry(view: View) {
//        onClickRetry?.invoke()
    }

//    fun noMore() {
//        binding.lLoad.visibility = View.VISIBLE
//        binding.lLoadStatus.loadMoreLoadingView.visibility = View.GONE
//        binding.lLoadStatus.loadMoreLoadEndView.visibility = View.VISIBLE
//        binding.lLoadStatus.loadMoreLoadFailView.visibility = View.GONE
//        binding.tv.visibility = View.GONE
//    }
//
//    fun loading() {
//        binding.lLoad.visibility = View.VISIBLE
//        binding.lLoadStatus.loadMoreLoadingView.visibility = View.VISIBLE
//        binding.lLoadStatus.loadMoreLoadEndView.visibility = View.GONE
//        binding.lLoadStatus.loadMoreLoadFailView.visibility = View.GONE
//        binding.tv.visibility = View.GONE
//    }
//
//    fun error() {
//        binding.lLoad.visibility = View.VISIBLE
//        binding.lLoadStatus.loadMoreLoadingView.visibility = View.GONE
//        binding.lLoadStatus.loadMoreLoadEndView.visibility = View.GONE
//        binding.lLoadStatus.loadMoreLoadFailView.visibility = View.VISIBLE
//        binding.tv.visibility = View.GONE
//        binding.lLoadStatus.loadMoreLoadFailView.setOnClickListener(::retry)
//    }

}